<template>
    <div class="warpper-box">
      <div class="inner_box">
       <form-create 
       v-model="params.fApi" 
       :rule="params.rule" 
       :option="params.option" 
       @btn-search-click="loadList(true)" 
       @btn-add-click="add(true)"
       @btn-del-click="delBatch"
       @btn-type1-change="function(val){return typeChange(val,'type2Id','params','2')}"
       @btn-type2-change="function(val){return typeChange(val,'type3Id','params','1')}"
       @btn-upload-click="uploadXlsx"
       @btn-reset-click="reset"/>
      <material-list
       :key="keys"
       :tableData="tables.tableData" 
       :tableLabel="tables.tableLabel" 
       :models="tables" 
       @on-search-click="loadList"
       @on-selection-click="selectionChange"
       @on-edit-click="add"
       @on-del-click="del"
       />
       <el-dialog :title="form.title" :visible.sync="form.visible" :width="form.width" :close-on-click-modal="false">
        <form-create 
        v-model="form.fApi" 
        :rule="form.rule" 
        :option="form.option"
        @btn-type1-change="function(val){return typeChange(val,'goodTypeId2','form','2')}"
        @btn-type2-change="function(val){return typeChange(val,'goodTypeId3','form','1')}"/>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="form.visible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="onFormSubmit">保存</el-button>
        </div>
      </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import store from '@/store'
  import { PARAMS_MATERIAL,FORM_MATERIAL,MATERIAL_LABEL,OPTION_BLOCK,OPTION_INLINE} from "./materialModel/material_form"
  import MaterialList from "./materialModel/material_model_list"
  import {getMaterialList,saveMaterialSave,delMaterial,delBatchMaterial} from "@/api/material_api"
  import { xlsx } from "@/utils/xlsx"
  export default {
    components:{
        MaterialList
    },
    data() {
      return {
        keys:0,
        params:{
          fApi:{},
          rule:PARAMS_MATERIAL,
          option:OPTION_INLINE
        },
        tables:{
          total:0,
          hackReset:true,
          fixed:'right',
          width:'180',
          tableData:[],
          tableLabel: MATERIAL_LABEL
        },
        form:{
          id:'',
          title:'新增物资',
          width:"1200px",
          visible:false,
          fApi:{},
          rule:[],
          option:OPTION_BLOCK
        },
        page:{
          pageNum:1,
          pageSize:10,
        },
        selectItem:[]
      };
    },
    mounted() {
      this.typeChange(0,'type1Id','params','all');
      this.loadList(true);
    },
    methods: {
      async typeChange(val,field,type,flag){
        //处理选择一级和二级时 清空子级数据
        if(type ==='params'){
          if(flag === 'all'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('type1Id', {options: []}, true);
              this[type].fApi.updateRule('type2Id', {options: []}, true);
              this[type].fApi.updateRule('type3Id', {options: []}, true);
              this[type].fApi.resetFields();
            })
          }else if(flag === '2'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('type2Id', {options: []}, true);
              this[type].fApi.updateRule('type3Id', {options: []}, true);
              this[type].fApi.setValue({'type2Id':'','type3Id':''});
            })
          }else if(flag === '1'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('type3Id', {options: []}, true);
              this[type].fApi.setValue({'type3Id':''});
            })
          }
        }else if(type === 'form'){
          if(flag === 'all'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('goodTypeId1', {options: []}, true);
              this[type].fApi.updateRule('goodTypeId2', {options: []}, true);
              this[type].fApi.updateRule('goodTypeId3', {options: []}, true);
              this[type].fApi.resetFields();
            })
          }else if(flag === '2'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('goodTypeId2', {options: []}, true);
              this[type].fApi.updateRule('goodTypeId3', {options: []}, true);
              this[type].fApi.setValue({'goodTypeId2':'','goodTypeId3':''});
            })
          }else if(flag === '1'){
            this.$nextTick(()=>{
              this[type].fApi.updateRule('goodTypeId3', {options: []}, true);
              this[type].fApi.setValue({'goodTypeId3':''});
            })
          }
        }
        let typeArr = await store.dispatch('user/getMaterialTypeSelect',val);
        this.$nextTick(()=>{
          this[type].fApi.updateRule(field, {options: typeArr}, true);
        });
      },
      async loadList(formData) {
        let params = this.params.fApi.bind();
        if(formData !== undefined && formData.type === 'page'){
          this.page.pageNum = formData.pageNum;
          this.page.pageSize = formData.pageSize;
        }
        if(formData===true){
          this.page.pageNum = 1;
          this.keys++;
        }
        params.pageNum = this.page.pageNum;
        params.pageSize = this.page.pageSize;
        const req = await getMaterialList(params);
        this.tables.tableData = req.data.list;
        this.tables.tableData.forEach(v=>{
          v.price = (v.price/100);
          v.edit=true;v.del=true;
        })
        this.tables.total = req.data.total;
      },
      
      add(row){
        this.form.rule = FORM_MATERIAL;
        if(row === true){
          this.form.title = "新增";
          this.form.id = "";
          this.typeChange(0,'goodTypeId1','form','all');
        }else{
          this.form.title = "编辑";
          this.form.id = row.id;
          this.typeChange(0,'goodTypeId1','form','');
          this.typeChange(row.goodTypeId1,'goodTypeId2','form','');
          this.typeChange(row.goodTypeId2,'goodTypeId3','form','');
          this.$nextTick(()=>{
            this.form.fApi.setValue({
              "name":row.name,
              "price":row.price,
              "unit":row.unit,
              "spec":row.spec,
              "code":row.code,
              "remarks":row.remarks,
              "goodTypeId1":row.goodTypeId1,
              "goodTypeId2":row.goodTypeId2,
              "goodTypeId3":row.goodTypeId3
            })
          })
        }
        this.form.visible = true;
      },

      async onFormSubmit(formData) {
        this.form.fApi.submit(async (formData, $f) => {
          try {
            let text = "新增成功";
            if(this.form.id){
              formData.id = this.form.id;
              text = "修改成功"
            }
            formData.price = (formData.price * 100)
            const {code,msg} = await saveMaterialSave(formData);
            if(code === 200){
              this.$message.success(text);
              this.form.visible = false;
              this.loadList();
            }
           
          } catch (error) {
            //this.$message.info(JSON.stringify(error));
          }
        })
      },
      del(row){
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          await delMaterial(row.id);
          this.$message.success("删除成功");
          this.loadList();
        }).catch(() => {});
      },
      selectionChange(arr){
        this.selectItem = arr;
      },
      delBatch(){
        if(this.selectItem.length === 0){
            return this.$message.error("请勾选要导出的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let ids = [];
          this.selectItem.forEach(v=>{
            ids.push(v.id)
          })
          const req = await delBatchMaterial(ids);
          if(req.code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
      },
      reset(){
        this.params.fApi.updateRule('type1Id', {options: []}, true);
        this.params.fApi.updateRule('type2Id', {options: []}, true);
        this.params.fApi.updateRule('type3Id', {options: []}, true);
        this.params.fApi.resetFields();
        this.loadList(true);
      },
      uploadXlsx(){
        const that = this;
        this.$prompt('请输入导出数量', '提示', {
          confirmButtonText: '导出',
          cancelButtonText: '取消',
          closeOnClickModal:false,
          inputPlaceholder:'导出数量不能大于列表总条数',
          inputValue:that.tables.total,
          inputValidator:function(val){
            if(!val){
              return false;
            }
            if(val > that.tables.total){
              return false;
            }else{
              return true;
            }
          },
          inputErrorMessage: '导出数量有误'
        }).then(async({ value }) => {
          let params = {};
          params.pageNum = 1;
          params.pageSize = value;
          const {code,data} = await getMaterialList(params);
          if(code === 200){
            if(data.list && data.list.length > 1){
              let fields = {
                title0: "编号",
                title1: "材料名称",
                title2: "材料编码",
                title3: "规格型号",
                title4: "单位",
                title5: "一级分类",
                title6: "二级分类",
                title7: "三级分类",
                title8: "单件/元",
                title9: "备注"
              };
              let arry = [];
              let i = 0;
              data.list.forEach(ele => {
                  i++;
                  arry.push({
                      title0: i,
                      title1: ele.name,
                      title2: ele.code,
                      title3: ele.spec,
                      title4: ele.unit,
                      title5: ele.type1Name,
                      title6: ele.type2Name,
                      title7: ele.type3Name,
                      title8: ele.price,
                      title9: ele.remarks,
                  });
              });
              xlsx(arry, fields, "物资列表");
            }
          }
        }).catch(() => {});
      }
    }
  };
  </script>